"""
模型画图
"""
import os
from pylab import *
from matplotlib import pyplot as plt
from keras.utils.vis_utils import plot_model


# 指定默认字体
mpl.rcParams['font.sans-serif'] = ['SimHei']
# 解决保存图像是负号'-'显示为方块的问题
mpl.rcParams['axes.unicode_minus'] = False


def explore_time_series(df_data):
    """
    数据探索，画出每列的时序图
    :param df_data:
    :return:
    """
    column_length = len(df_data.columns)

    plt.clf()
    plt.figure()
    for i in range(column_length):
        column = df_data.columns[i]
        # n行1列
        plt.subplot(column_length, 1, i + 1)
        plt.plot(df_data[column])
        plt.title(column, y=0.5, loc='right')

    plt.show()


def keras_plot_model(model, pic, show_shapes=True, show_layer_names=True,
                     expand_nested=True, dpi=96):
    """
    keras 模型画图
    :param model:
    :param pic:
    :param show_shapes:
    :param show_layer_names:
    :param expand_nested:
    :param dpi:
    :return:
    """
    # 增加Graphviz环境
    graphviz_path = 'D:/Program Files/Graphviz 2.44.1/bin'
    # os.environ["PATH"] += os.pathsep + graphviz_path
    os.environ["PATH"] += ';{}'.format(graphviz_path)

    if not os.path.isfile(pic):
        plot_model(model,
                   show_shapes=show_shapes,
                   show_layer_names=show_layer_names,
                   expand_nested=expand_nested,
                   dpi=dpi,
                   to_file=pic)


def plot_model_graph(model_fit, model_name, pic_path):
    """
    模型训练过程的loss (and acc)
    :param model_fit:
    :param model_name:
    :param pic_path:
    :return:
    """

    def plot_info(train, test, title, ylabel, pic_path):
        """
        训练 & 测试
        :param train:
        :param test:
        :param title:
        :param ylabel:
        :param pic_path:
        :return:
        """
        plt.clf()

        plt.plot(train)
        plt.plot(test)
        plt.title(title)
        plt.xlabel('Epoch')
        plt.ylabel(ylabel)
        plt.legend(['训练', '测试'], loc='upper left')

        pic = '{}/{}.png'.format(pic_path, title)
        if not os.path.isfile(pic):
            plt.savefig(pic)
        # plt.show()

    # loss
    train_loss = model_fit.history['loss']
    test_val_loss = model_fit.history['val_loss']
    plot_info(train=train_loss, test=test_val_loss,
              title=model_name + ' 模型损失值',
              ylabel='Loss',
              pic_path=pic_path)

    # acc
    if 'acc' in model_fit.history.keys():
        train_acc = model_fit.history['acc']
        test_val_acc = model_fit.history['val_acc']
        plot_info(train=train_acc, test=test_val_acc,
                  title=model_name + ' 模型准确率',
                  ylabel='Accuracy',
                  pic_path=pic_path)
